package com.binbinyl.model.local.sp

import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.binbinyl.helper.DeviceUtil
import com.binbinyl.helper.Util

/**
 * SharedPreference数据存储具体实现类
 */
object SpHelper : IPreferenceHelper {
    private const val PREF_KEY_USER_LOGGED_IN_MODE = "login_mode"
    private const val PREF_KEY_USER_ID = "uid"
    private const val PREF_KEY_TOKEN = "token"
    private const val PREF_KEY_DEVICE_ID = "device_id"


    const val DEFAULT_INT_VALUE_NON = 0

    lateinit var sp: SharedPreferences

    fun init(context: Context) {
        sp = PreferenceManager.getDefaultSharedPreferences(context)
    }

    override fun getLoginMode(): Int {
        return sp.getInt(PREF_KEY_USER_LOGGED_IN_MODE, DEFAULT_INT_VALUE_NON)
    }

    override fun getUid(): Int {
        return sp.getInt(PREF_KEY_USER_ID, DEFAULT_INT_VALUE_NON)
    }

    override fun getToken(): String {
        return sp.getString(PREF_KEY_TOKEN, "")
    }

    override fun saveToken(token: String) {
        sp.edit().putString(PREF_KEY_TOKEN, token).apply();
    }

    override fun getDeviceId(context: Context): String {
        val devId = sp.getString(PREF_KEY_DEVICE_ID, "")
        if (Util.checkNull(devId)) {
            return DeviceUtil.fetchMyDeviceId(context)
        }
        return devId
    }
}